package com.haiya.identityaccess.infrastructure.persistence.mybatis.repository;

import com.haiya.identityaccess.domain.identity.model.Group;
import com.haiya.identityaccess.domain.identity.model.TenantId;
import com.haiya.identityaccess.domain.identity.repository.GroupRepository;
import com.haiya.identityaccess.infrastructure.persistence.mybatis.datamodel.DataGroup;
import com.haiya.identityaccess.infrastructure.persistence.mybatis.mapper.GroupMapper;
import com.haiya.identityaccess.infrastructure.persistence.mybatis.translation.GroupTranslate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author qiaoguoqiang
 */
@Repository
public class GroupRepositoryImpl implements GroupRepository {
    @Autowired
    GroupMapper groupMapper;

    @Override
    public void add(Group aGroup) {
        DataGroup dataGroup = GroupTranslate.toDataEntity(aGroup);
        groupMapper.insert(dataGroup);
    }

    @Override
    public Collection<Group> allGroups(TenantId aTenantId) {
        List<DataGroup> dataGroups = groupMapper.allGroups(aTenantId.id());
        Collection<Group> groups = new ArrayList<>();
        for (DataGroup dataGroup : dataGroups) {
            Group group = GroupTranslate.toDomainEntity(dataGroup);
            groups.add(group);
        }
        return groups;
    }

    @Override
    public Group groupNamed(TenantId aTenantId, String aName) {
        DataGroup dataGroup = groupMapper.groupNamed(aTenantId.id(), aName);
        if (dataGroup != null) {
            return new Group(aTenantId, dataGroup.getName(), dataGroup.getDescription());
        }
        return null;
    }

    @Override
    public void remove(Group aGroup) {
        groupMapper.removeNamed(aGroup.tenantId().id(), aGroup.name());
    }
}
